package com.whzykj.model;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.whzykj.common.DateUtil;
import com.whzykj.common.DbUtil;
import com.whzykj.common.SnUtil;
import com.whzykj.jfinal.TableBind;

@TableBind(name = "orderinfo", pk = "order_id")
public class OrderInfo extends Model<OrderInfo> {
	private static final long serialVersionUID = 1L;
	public static final OrderInfo me = new OrderInfo();

	// 查询订单列表
	public List<OrderInfo> getOrder(String userid, String orderid) {
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT * FROM orderinfo where 1=1 ");
		if (userid != null && !"".equals(userid)) {
			sbf.append(" and user_id=" + userid + " ");
		}
		if (orderid != null && !"".equals(orderid)) {
			sbf.append(" and order_id='" + orderid + "' ");
		}
		sbf.append(" order by order_date desc ");
		return OrderInfo.me.find(sbf.toString());
	}

	// 查询订单列表
	public List<OrderInfo> getOrderlist(String userid) {
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT o.*,c.CUST_NAME FROM orderinfo o LEFT JOIN customer c ON o.CUST_ID=c.CUST_ID ORDER BY order_date DESC ");
		return OrderInfo.me.find(sbf.toString());
	}

	// 查询超过一小时未处理订单
	public List<Record> getOrder() {
		String sql = " SELECT r.ORDER_DATE,s.* FROM orderinfo r,orderdetails s WHERE r.ORDER_ID=s.ORDER_ID AND r.STATUS='no_pay' ";
		return Db.find(sql);
	}
	
	/**
	 * 关闭订单,并同时恢复库存信息
	 * @param orderid
	 * @return
	 */
	public int closeOrder(String orderid){		
		int res=0;			// 	0：表示订单关闭失败
//		 Config config = getConfig();
		List<String> sqlList=new ArrayList<String>();
		String sql="UPDATE orderinfo SET STATUS='over' WHERE ORDER_ID='"+orderid+"'";
		sqlList.add(sql);
		String sql0="select od.*,oi.order_date FROM orderdetails od  INNER JOIN orderinfo oi on oi.order_id=od.order_id where od.order_id=?";
		List<OrderDetails> list=OrderDetails.me.find(sql0,orderid);
		StringBuffer sb=null;
		if(list!=null && list.size()>0){
			for(OrderDetails od:list){
				String date=od.getTimestamp("order_date").toString().substring(0,10);
				sb=new StringBuffer(" update store set SALE_NUM=SALE_NUM-"+od.getInt("SALE_NUM"));
				sb.append(" WHERE SET_DATE='"+date+"'");
				sb.append("  AND GOODS_ID="+od.getInt("GOODS_ID"));
				sqlList.add(sb.toString());
				sb=null;
			}
		}
		OrderInfo orderinfo=OrderInfo.me.findById(orderid);
		String status=orderinfo.getStr("status");
		if(status!=null && status.equals("nosend")){
			int cust_id=orderinfo.getInt("cust_id");
			int userid=orderinfo.getInt("user_id");
			PayBill paybill=PayBill.dao.findFirst("SELECT * from paybill pb where order_id='"+orderid+"'");
			if(paybill!=null){
				String sn=SnUtil.getSn("UP");	// 生成撤销交易流水编号
				double update_amount=paybill.getBigDecimal("amount").doubleValue();
				sb=new StringBuffer("update paybill SET pay_state='01' WHERE SN='"+paybill.getStr("sn")+"'");
				sqlList.add(sb.toString());		// 更新支付流水的状态为撤销订单
				
				sb=new StringBuffer("INSERT INTO undopaybill VALUES('"+sn+"',"+paybill.getInt("acct_id")+",'"+paybill.getStr("sn")+"','"+orderid+"',"+update_amount+",");
				sb.append("'订单关闭','"+DateUtil.getNow()+"',"+userid+",'"+DateUtil.getNow()+"',"+userid+",'01','已付款订单人工关闭')");
				sqlList.add(sb.toString());		// 将关闭订单的记录保存到撤销交易的记录里面
				Account acct=Account.dao.findById(paybill.getInt("acct_id"));
				double pamount=acct.getBigDecimal("amount").doubleValue();
				double aamount=pamount+update_amount;
				sb=new StringBuffer("insert INTO account_seq VALUES('"+SnUtil.getSn("ZJ")+"',"+paybill.getInt("acct_id")+",'00','09',"+pamount+","+aamount+",'"+sn+"','"+DateUtil.getNow()+"',NULL,NULL)");
				sqlList.add(sb.toString());		// 记入资金变动流水
				// 更改账户表中的金额信息
				sqlList.add("UPDATE account set amount=amount+"+update_amount+",last_update_time='"+DateUtil.getNow()+"',last_update_person="+userid+" where acct_id="+paybill.getInt("acct_id"));
			}
		}
		try {
//			int[] cnts=Db.batch(sqlList, 100);
			boolean result=DbUtil.batch(sqlList);
			res=1;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res=0;
		}
		return res;
	}

}
